const { UserPoint, PointRecord } = require("@models/point");
const { User } = require("@models/user");
const { Rebate } = require("@models/rebate");
const { sequelize } = require("@core/db");
const { where } = require("sequelize");

class operatorPoint {
  //获取总积分
  static async getPoint_count(uid) {
    // let sql = `SELECT SUM(point) AS point FROM user_point WHERE uid = ${uid};`;
    // let count_point = await sequelize.query(sql, {
    //   type: QueryTypes.SELECT,
    // });
    const count_point = await UserPoint.findAll({
      where: { uid },
      attributes: [[sequelize.fn("SUM", sequelize.col("point")), "point"]],
    });

    await User.update(
      {
        point: count_point[0].point || 0, //累加获得用户积分
      },
      {
        where: { uid: uid },
      }
    );
    return count_point[0].point || 0;
  }

  // 添加积分
  static async add(user, point, remark) {
    // 添加积分
    const userpoint = await UserPoint.create({
      point: point,
      remark: `${remark}${point}积分`,
      operator_id: user.uid,
      uid: user.uid,
    });
    // 获取当前积分
    const count_point = await this.getPoint_count(user.uid);
    // 生成积分记录
    await PointRecord.create({
      add_point: point,
      current_point: count_point,
      remark,
      operation: `${remark}${point}积分，当前积分为${count_point}`,
      uid: user.uid,
    });
  }

  // 核销添加积分

  static async add_scan(point, uid) {
    const userpoint = await UserPoint.create({
      point: point,
      remark: `核销返利${point}积分`,
      operator_id: 1,
      uid: uid,
    });
    // 获取当前积分
    const count_point = await this.getPoint_count(uid);
    // 生成积分记录
    await PointRecord.create({
      add_point: point,
      current_point: count_point,
      remark: `核销返利`,
      operation: `用户获得${point}积分，当前积分为${count_point}`,
      uid: uid,
    });
  }
  // 产品添加积分
  static async add_point(user, product, operator_id) {
    // 添加用户积分
    const userpoint = await UserPoint.create({
      point: product.product_point,
      remark: "购买了" + product.product_name,
      operator_id,
      uid: user.uid,
    });

    // 获取用户总积分
    const count_point = await this.getPoint_count(user.uid);

    // 添加积分记录
    await PointRecord.create({
      add_point: product.product_point,
      current_point: count_point,
      remark: "购买了" + product.product_name,
      operation: `添加了${product.product_point}积分，当前积分为${count_point}`,
      operator_id,
      uid: user.uid,
    });

    // 如果存在上级用户，则给上级用户返利
    if (user.pid) {
      const rebate_point = product.product_point * product.proportion;
      // 获取上级用户
      const user_p = await User.findOne({ where: { uid: user.pid } });
      // 如果上级是销售则添加返现记录
      if (user_p.power >= 7) {
        // 添加返利记录
        await Rebate.create({
          pid: user.pid,
          uid: user.uid,
          admin_id: operator_id,
          user_point_id: userpoint.user_point_id,
          product_id: product.product_id,
          remark: "购买了" + product.product_name,
          rebate_money: rebate_point,
        });
      }

      // 如果上级是普通用户则直接返积分
      if (user_p.power < 7) {
        // 返利积分
        await UserPoint.create({
          point: rebate_point,
          remark: "返利积分",
          operator_id,
          uid: user.pid,
        });

        let p_point = await this.getPoint_count(user.pid);
        // 生成积分记录
        await PointRecord.create({
          add_point: rebate_point,
          current_point: p_point,
          remark: "积分返利",
          operation: `${user.user_name}购买${product.product_name},返利${rebate_point}积分`,
          operator_id,
          uid: user.pid,
        });
      }
    }
  }

  // 删除积分
  static async del_point(uid, operator_id) {
    const user_point = await UserPoint.findOne({
      where: { uid },
    });

    await user_point.destroy({
      force: true,
    });

    await Rebate.destroy({
      where: {
        user_point_id: user_point.user_point_id,
      },
      force: true,
    });

    const count_point = await this.getPoint_count(uid);

    await PointRecord.create({
      remove_point: point,
      current_point: count_point,
      operation: `删除了${point}积分，当前积分为${count_point}`,
      remark: "删除积分",
      operator_id,
      uid,
    });
  }

  // 消费积分
  static async consume_point(uid, remark, point, operator_id = 0) {
    let pt = point;
    const user_point = await UserPoint.findAll({
      where: {
        uid: uid,
      },
      order: [["created_at", "DESC"]],
    });

    // 获取用户积分
    let current_point = await this.getPoint_count(uid);

    if (current_point - point < 0) {
      throw new global.errs.AuthFailed("用户积分不足");
    }

    // 获取用户积分列表
    let user_point_count = JSON.parse(JSON.stringify(user_point));

    for (let i = 0; i < user_point_count.length; i++) {
      if (user_point_count[i].point - point > 0) {
        await UserPoint.update(
          { point: user_point_count[i].point - point },
          {
            where: { user_point_id: user_point_count[i].user_point_id },
          }
        );
        break;
      }
      if (user_point_count[i].point - point == 0) {
        await UserPoint.destroy({
          where: { user_point_id: user_point_count[i].user_point_id },
        });
        break;
      }
      if (user_point_count[i].point - point < 0) {
        await UserPoint.destroy({
          where: { user_point_id: user_point_count[i].user_point_id },
        });
        point = point - user_point_count[i].point;
      }
    }

    current_point = await this.getPoint_count(uid);

    await PointRecord.create({
      remove_point: pt,
      current_point: current_point,
      operation: `消费了${pt}积分，当前积分为${current_point}`,
      remark,
      operator_id,
      uid,
    });
  }
}

module.exports = {
  operatorPoint,
};
